package com.example.aigc_education.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.domain.User;
import com.example.aigc_education.mapper.MenuMapper;
import com.example.aigc_education.mapper.UserMapper;
import com.example.aigc_education.security.domain.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户加载校验
 */
@Slf4j
@Service
public class MobileUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    /**
     * 查询用户信息
     * @param phone 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException usernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        log.info("手机号登录，手机号：{}", phone);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        List<String> permsList = menuMapper.selectPermsByUserId(user.getUserId());
        log.info("用户编号{}权限:{}", user.getUserId(), permsList);
        return new LoginUser(user, permsList);
    }
}
